package com.jdaw.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.jdaw.reggie.common.BaseContext;
import com.jdaw.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.juli.logging.Log;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *检查是否完成登录
 */

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")//配置拦截url，这里拦截所有
@Slf4j
public class LoginCheckFilter implements Filter {
    //定义路径匹配器
    public static final AntPathMatcher ANT_PATH_MATCHER=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;

        //获取请求uri，判断是否处理，处理的话就检查是否登录，已登录就放行，未登录跳转
        String requestURI = request.getRequestURI();
        //定义不需要处理的uri
        String[] urls=new String[]{
              "/employee/login",
              "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",
                "/user/sendMsg"
        };
        boolean check=check(urls,requestURI);
        if(check){
            filterChain.doFilter(request,response);
            return;
        }
        if(request.getSession().getAttribute("employee")!=null){
            Long empId=(Long)request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request,response);
            return;
        }
        //判断移动端用户是否已登录
        if(request.getSession().getAttribute("user")!=null){
            Long userId=(Long)request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        //若未登录，因为前端有方法，若后端传回的res.data.code==0就会自动跳转
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

        return;
    }

    /*判断的方法
    * */
    public boolean check(String[] urls,String requestURI){
        for(String url:urls){
            boolean match=ANT_PATH_MATCHER.match(url,requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }

}
